users = function(){

    var ajaxUrl = AdMin.base_url +"/modules/users/admin/ajax.php";
    var ucfirst = function (str) { str += ''; return str.charAt(0).toUpperCase() + str.substr(1); }
    var renderActive = function (val) { return '<span class="ico_'+ val +'"></span>'; }
    var renderSuperuser = function (val) { return '<span class="ico_'+ val +'"></span>'; }
    var deleteUser = function (btn) {
        if(btn=='yes') {
            var slctn = usersGrid.getSelectionModel().getSelections();
            for(var i = 0, record, arPIDs = Array(); record = slctn[i]; i++) {
                arPIDs.push(record.data.userID);
            }
            Ext.Ajax.request({
               url: ajaxUrl +'?c=users&action=delete',
               success: function() {
                   usersStore.reload();
                   userDetailsForm.getForm().reset();
                   userDetailsForm.disable();
                   Ext.AdMin.msg(AdMin.lang.translate("status"),AdMin.lang.translate("status"))
				},
				failure: function() {
					Ext.Msg.show({
						title: AdMin.lang.translate("error_delete_record"),
                        msg: res.message,
						icon: Ext.MessageBox.ERROR
					});
				},
				params: { 'userID[]': arPIDs }
            });
        }
    };

    var deleteRole = function (btn) {
        if(btn=='yes') {
            var roleID = rolesGrid.getSelectionModel().getSelected().get("roleID");
            Ext.Ajax.request({
               url: ajaxUrl +'?c=roles&action=delete_role',
               method : "GET",
               params: { roleID: roleID},
               callback : function (options, success, response) {
                    var obj = Ext.util.JSON.decode(response.responseText);
                    if(!obj.success) {
                        Ext.Msg.alert("error", obj.data);
                    }
                    rolesStore.reload();
                }
            });
        }
    };

    /*
    * DATA STORES
    *
    * USERS STORE
    */
    var usersStore = new Ext.data.JsonStore({
        root: 'users',
        totalProperty: 'totalCount',
        idProperty: 'userID',
        autoDestroy: true,
        remoteSort: true,
        fields: [{name:'userID', type: 'int'}, 'username', 'name', 'last_name', 'email', 'roles', 'active', 'superuser', 'last_login', 'date_created'],
        url: ajaxUrl +'?c=users&action=user_list'
    });
    usersStore.setDefaultSort('username', 'asc');

    /*
    * ROLES STORE
    */
    var rolesStore = new Ext.data.JsonStore({
        root: 'data',
        autoLoad : true,
        totalProperty: 'total',
        idProperty: 'roleID',
        autoDestroy: true,
        remoteSort: true,
        fields: ['roleID', 'description', 'users'],
        url: ajaxUrl +'?c=roles&action=role_list'
    });

    /*
    * GRID
    */
    var colModel = new Ext.grid.ColumnModel({
        defaults: { sortable: true },
        columns: [
            {header: "id", width: 45, dataIndex: 'userID'},
            {header: AdMin.lang.translate('username'), width: 100, dataIndex: 'username', handler: function(){ location.href="abm.php"; }},
            {header: AdMin.lang.translate('name'), width: 100, dataIndex: 'name', hidden: true},
            {header: AdMin.lang.translate('last_name'), width: 150, dataIndex: 'last_name', hidden: true},
            {header: AdMin.lang.translate('email'), width: 200, dataIndex: 'email', hidden: true},
            {id:'roles', header: AdMin.lang.translate('roles'), width: 150, dataIndex: 'roles'},
            {header: AdMin.lang.translate('active'), width: 67, renderer:renderActive, dataIndex: 'active'},
            {header: AdMin.lang.translate('superuser'), width: 100, renderer:renderSuperuser, dataIndex: 'superuser'},
            {header: AdMin.lang.translate('last_login'), width: 110, dataIndex: 'last_login'},
            {header: AdMin.lang.translate('date_created'), width: 110, dataIndex: 'date_created', hidden: true}
        ]
    });

    var newUserWin = new Ext.Window({
        width : 800,
        height : 400,
        border : false,
        items : [{
            xtype : "form",
            id : "new-user-form",
            url : "aaa",
            items : [{
                layout : "column",
                border : false,
                defaults : {
                    layout: "form",
                    border: false,
                    columnWidth: 0.5,
                    bodyStyle: "padding:10px"
                },
                items : [{   // column 1
                    xtype : "fieldset",
                    title : "Info de sistema",
                    items : [
                        { xtype : "textfield", fieldLabel : "user_name", name : "user_name" },
                        { xtype : "textfield", fieldLabel : "password",  inputType : "password", name : "password" },
                        { xtype : "textfield", fieldLabel : "password_confirm", inputType : "password", name : "password_confirm" }
                    ]
                },{   // column 2
                    xtype : "fieldset",
                    title : "Datos personales",
                    items : [
                        { xtype : "textfield", fieldLabel : "name", name : "name" },
                        { xtype : "textfield", fieldLabel : "last_name", name : "last_name" },
                        { xtype : "textfield", fieldLabel : "password", inputType : "password", name : "password" },
                        { xtype : "textfield", fieldLabel : "password_confirm", inputType : "password", name : "password_confirm" }
                    ]
                }]
            }],
            buttons : [{
                text : "save",
                handler : function () {
                    Ext.getCmp("new-user-form").getForm().submit();
                }
            }]
        }]
    });

    var usersGrid = new Ext.grid.GridPanel({
        flex : 1,
        border : false,
        store: usersStore,
        columnLines: true,
        stripeRows: true,
        autoExpandColumn: 'roles',
        loadMask: true,
        // Columns and CheckboxSelectionModel plugin
        cm: colModel,
        selModel : new Ext.grid.RowSelectionModel({singleSelect:true}),
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: AdMin.users.numMaxListedRows,
            store: usersStore,
            displayInfo: true,
            displayMsg: AdMin.lang.translate('displayin_n-m_of_p'),
            emptyMsg: AdMin.lang.translate('no_records_found')
        })
    });

    var usersPanel = new Ext.Panel({
        region : "center",
        layout : "vbox",
        border : true,
        margins: '5 0 5 5',
        layoutConfig: {
            align : 'stretch',
            pack  : 'start'
        },
        split : true,
        title: ucfirst(AdMin.lang.translate('users')),
        // task bar
        tbar: [{
            iconCls: 'silk-add',
            text: AdMin.lang.translate("add"),
            handler: function() {
                usersStore.add(
                    new Ext.data.Record({
                        'userID':null,
                        'username':"",
                        'name':"",
                        'last_name':"",
                        'email':"",
                        'roles':"",
                        'active':"",
                        'superuser':"",
                        'last_login':"",
                        'date_created':""
                    })
                );

                usersGrid.getSelectionModel().selectLastRow();
                Ext.getCmp("userDetailsForm-username").getEl().focus();
                new Ext.ToolTip({
                    target: Ext.getCmp("userDetailsForm-username").getEl(),
                    anchor: 'top',
                    html: 'Nuevo usuario!'
                }).show();
            }
        },
        '-',
        {
            ref: '../removeBtn',
            iconCls: 'silk-delete',
            text: AdMin.lang.translate("delete"),
            disabled: true,
            handler: function() {
                Ext.MessageBox.confirm(AdMin.lang.translate('warning'),  AdMin.lang.translate('are_you_sure_to_delete'), deleteUser);
            },
            tooltip: AdMin.lang.translate("click_here_to_delete_selected")
        },
        '-',
        AdMin.lang.translate('search'),
        new Ext.app.SearchField({
            id : "users-search-field",
            store: usersStore,
            width:290
        })],
        bodyStyle : "background-color:  #E5EDF8;",
        items : [ usersGrid ]
    });

    usersGrid.getSelectionModel().on('selectionchange', function(sm) {
        usersPanel.removeBtn.setDisabled(sm.getCount() < 1);
    });

    usersGrid.getSelectionModel().on('rowselect', function(sm, idx, r){
        userDetailsForm.enable();
        Ext.getCmp("userDetailsForm-last-login").disable();
        Ext.getCmp("userDetailsForm-user-created").disable();
        Ext.getCmp("userDetailsForm-date-created").disable();
        Ext.getCmp("userDetailsForm-user-modified").disable();
        Ext.getCmp("userDetailsForm-date-modified").disable();
        userDetailsForm.load({
            url: ajaxUrl +"?c=users",
            method: "get",
            params : {
                responseType: "ajax",
                action: "details",
                userID: r.get("userID")
            }
        });
    });
    usersStore.load({params:{start:0, limit: AdMin.users.numMaxListedRows}});

    // roles grid
    var rolesEditor = new Ext.ux.grid.RowEditor({
        saveText: 'Update',
        errorSummary : false
    });

    // ROLES EDITOR EVENTS
    rolesEditor.on("canceledit", function(obj, changes, r, rowIndex) { rolesStore.reload(); if(obj.onCancel) obj.onCancel();}    );
    rolesEditor.on("afteredit", function(obj, changes, r, rowIndex) {
        Ext.Ajax.request({
            url: ajaxUrl +'?c=roles&action=save_role',
            method : "GET",
            params: {
                roleID: r.get("roleID"),
                description : r.get("description")
            },
            callback : function (options, success, response) {
                var obj = Ext.util.JSON.decode(response.responseText);
                if(!obj.success) Ext.Msg.alert("error", obj.data);
                rolesStore.reload();
            }
        });
    });

    /*
    * ROLES GRID
    */
    var rolesGrid = new Ext.grid.GridPanel({
        loadMask : AdMin.lang.translate("loading")+"...",
        region : "center",
        store : rolesStore,
        border : true,
        margins: '5 0 5 5',
        title: ucfirst(AdMin.lang.translate('role_list')),
        plugins : rolesEditor,
        autoExpandColumn: "users",
        selModel : new Ext.grid.RowSelectionModel({singleSelect:true}),
        tbar: [{
            iconCls: 'silk-add',
            text: AdMin.lang.translate("add"),
            handler: function() {
                var e = new Ext.data.Record({'roleID':""});
                Ext.getCmp("roleID-editor").enable();
                rolesEditor.stopEditing();
                rolesStore.insert(0, e);
                rolesGrid.getView().refresh();
                rolesGrid.getSelectionModel().selectRow(0);
                rolesEditor.startEditing(0);
            }
        },
        '-',
        {
            ref: '../removeBtn',
            id : "btn-role-delete",
            iconCls: 'silk-delete',
            text: AdMin.lang.translate("delete"),
            disabled: true,
            handler: function() {
                Ext.MessageBox.confirm(AdMin.lang.translate('warning'),  AdMin.lang.translate('are_you_sure_to_delete'), deleteRole);
            },
            tooltip: AdMin.lang.translate("click_here_to_delete_selected")
        }],
        cm: new Ext.grid.ColumnModel({
            defaults: { sortable: true },
            columns: [
                {header: "roleID", width:200, dataIndex : "roleID", editor: { id : "roleID-editor", xtype: 'textfield'}},
                {header: "description", width: 400, dataIndex : "description", editor: { xtype: 'textfield'}},
                {header: "users", width: 400, dataIndex : "users", id : "users"}
            ]
        })
    });
    rolesGrid.getSelectionModel().on('rowselect', function(sm, idx, r){
        Ext.getCmp('btn-role-delete').enable();
        rolePermissionsForm.load({ url: ajaxUrl +"?c=roles", params : {action : "get_role_perm", responseType:"ajax",roleID : r.get("roleID") } });
        rolePermissionsForm.enable();
    });

    /*
    * ROLE PERMISSIONS FORM
    */
    var rolePermissionsForm = new Ext.FormPanel({
        region : "east",
        border : true,
        margins: '5 5 5 0',
        width : 600,
        id : "users-module-role-permissionsform",
        disabled : true,
       // style : "font-family: arial,tahoma,helvetica,sans-serif; font-size: 11px; ",
        bodyStyle : "padding:10px;font-size: 11px;",
        split : true,
        title : AdMin.lang.translate("editing_role"),
        url : ajaxUrl+"?c=roles&action=set_role_perm",
        method : "GET",
        autoScroll : true,
        items : [AdMin.users.roleActionsFormFields],
        bbar : [
            "->",
            {
                iconCls: 'silk-save',
                id : "role-btn-save",
                text : "save",
                handler : function () {
                    rolePermissionsForm.getForm().submit();
                }
            }
        ]
    });

    /*
    * USERS FORM
    */
    var userDetailsForm = new Ext.FormPanel({
        region : "east",
        id : "userDetailsForm",
        border : true,
        margins: '5 5 5 0',
        labelWidth: 80, // label settings here cascade unless overridden
        url : ajaxUrl+"?c=users&action=save_details",
        title: AdMin.lang.translate('details'),
        defaultType: 'textfield',
        width : 400,
        split : true,
        disabled : true,
        autoScroll : true,
        bodyStyle:'padding:10px',
        items :[{
            xtype : "fieldset",
            id : "userDetailsForm-fieldset",
            title : "Datos personales",
            defaultType : "textfield",
            items: [
                { name: 'userID', xtype : 'hidden' },
                { fieldLabel: 'username', name: 'username', id :"userDetailsForm-username"},
                { fieldLabel: 'name', name: 'name'},
                { fieldLabel: 'last_name', name: 'last_name'},
                { fieldLabel: 'email', name: 'email', vtype:'email' },
                { fieldLabel: 'superuser', name: 'superuser',xtype : "checkbox", inputValue : "Y"},
                { fieldLabel: 'active', name: 'active', xtype : "checkbox", inputValue : "Y"},
                { fieldLabel: 'Update password', name: 'password', inputType:'password'}
            ]
        },{
            xtype : "fieldset",
            id : "user-system-info",
            title : "system_info",
            labelWidth: 80, // label settings here cascade unless overridden
            items: [{
                disabled : true,
                id : "userDetailsForm-last-login",
                fieldLabel: 'last_login',
                xtype:'xdatetime',
                name : 'last_login',
                anchor:'-18',
                timeFormat:'H:i:s',
                timeConfig: { altFormats:'H:i:s', allowBlank:true},
                dateFormat:'d/m/Y',
                dateConfig: { altFormats:'Y-m-d|Y-n-d', allowBlank:true }
            },{
                xtype : "textfield",
                width:140,
                fieldLabel: 'user_created',
                name: 'user_created',
                id :"userDetailsForm-user-created"
            },{
                disabled : true,
                id : "userDetailsForm-date-created",
                fieldLabel: 'date_created',
                xtype:'xdatetime',
                name : 'date_created',
                anchor:'-18',
                timeFormat:'H:i:s',
                timeConfig: { altFormats:'H:i:s', allowBlank:true},
                dateFormat:'d/m/Y',
                dateConfig: { altFormats:'Y-m-d|Y-n-d', allowBlank:true }
            },{
                xtype : "textfield",
                width:140,
                fieldLabel: 'user_modified',
                name: 'user_modified',
                id :"userDetailsForm-user-modified"
            },{
                disabled : true,
                id : "userDetailsForm-date-modified",
                fieldLabel: 'date_modified',
                xtype:'xdatetime',
                name : 'date_modified',
                anchor:'-18',
                timeFormat:'H:i:s',
                timeConfig: { altFormats:'H:i:s', allowBlank:true},
                dateFormat:'d/m/Y',
                dateConfig: { altFormats:'Y-m-d|Y-n-d', allowBlank:true }
            }]
        },{
            xtype : "fieldset",
            id : "user-roles",
            title : "Roles",
            defaultType : "checkbox",
            labelWidth : 200,
            items: []
        }],
        bbar : [
            "->",
            {
                iconCls: 'silk-save',
                id : "user-btn-save",
                text : "save",
                handler : function () {
                    userDetailsForm.getForm().submit({
                        success: function(form, action) {
                            var result=Ext.util.JSON.decode(action.response.responseText);
                            if(result.success) {
                                var userID = result.data.userID;
                                usersStore.reload({
                                    scope : this,
                                    callback : function () {
                                        record = usersStore.getById(userID);
                                        usersGrid.getSelectionModel().selectRecords([record]);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        ]
    });

    var loadRoles = function (roles) {
        rolesFieldSet = Ext.getCmp("user-roles");
        rolesFieldSet.removeAll();
        Ext.each(roles, function (role) {
            rolesFieldSet.add(new Ext.form.Checkbox({
                labelWidth :200,
                fieldLabel: role,
                name: "roles[" + role.split(' ').join('_') + "]",
                xtype : 'checkbox',
                inputValue:'Y'
            }));
        });
    }
    loadRoles(AdMin.users.roles);

    /*
    * USER'S LOGS
    */
    var logFields = ['logID', 'status', 'module', 'task', 'target', 'start_comment', 'end_comment', 'userID', 'date_created', 'username']
    var logStore = new Ext.data.JsonStore({
        root: 'data',
        baseParams : {
            module : "",
            user : "",
            datef : "",
            datet :""
        },
        totalProperty: 'total',
        autoDestroy: true,
        fields: logFields,
        url: ajaxUrl +'?c=log&action=log_list'
    });

    var logGrid = new Ext.ListView({
        region : "center",
        border : true,
        columnSort : false,
        multiSelect : false,
        simpleSelect : false,
        autoHeight : true,
        style : "background-color: #fff;overflow:auto",
        columns : [
            {header:"logID", sortable : true, width: .05,  dataIndex :"logID",hidden:false},
            {header:"username", sortable : true,width : .08,  dataIndex :"username",hidden:false, dataType :"text"},
            {header:"date_created", sortable : true,width : .1,  dataIndex :"date_created",hidden:false, dataType :"text"},
            {header:"status", sortable : true, width: .05,  dataIndex :"status",hidden:false},
            {header:"module", sortable : true,width : .1,  dataIndex :"module",hidden:false,dataType :"text"},
            {header:"task", sortable : true,width : .1,  dataIndex :"task",hidden:false, dataType :"text"},
            {header:"target", sortable : true,width : .1,  dataIndex :"target",hidden:false, dataType :"text"},
            {header:"start_comment", sortable : true,width : .21,  dataIndex :"start_comment",hidden:false, dataType :"text"},
            {header:"end_comment", sortable : true,width : .21,  dataIndex :"end_comment",hidden:false, dataType :"text"}
        ],
        border : false,
        autoScroll : true,
        layout : "fit",
        viewConfig:{forceFit:true},
        selModel : new Ext.grid.RowSelectionModel({ singleSelect:true }),
        store : logStore
    });

    var logPanel = new Ext.Panel({
        border : false,
        layout: "border",
        id : "log-tab",
        bodyStyle : "overflow-y: auto",
        tbar : [
            new Ext.Toolbar.TextItem(AdMin.lang.translate("module")+":"),
            {
                xtype: "combo",
                id: "filter-module",
                layout: "form",
                typeAhead: true,
                triggerAction: 'all',
                lazyRender:true,
                mode: 'local',
                store: new Ext.data.JsonStore({
                    fields: [ 'id', 'name' ],
                    data: AdMin.modules
                }),
                valueField: 'id',
                displayField: 'name'
            }
            ,"-",
            new Ext.Toolbar.TextItem(AdMin.lang.translate("user")+":"),
            {
                xtype : "combo",
                id : "filter-user",
                layout : "form",
                typeAhead: true,
                triggerAction: 'all',
                lazyRender:true,
                mode: 'local',
                store: new Ext.data.ArrayStore({
                    id: 0,
                    fields: [ 'userID', 'username' ],
                    data: AdMin.users.userNames
                }),
                valueField: 'userID',
                displayField: 'username'
            },
            "-",
            new Ext.Toolbar.TextItem (AdMin.lang.translate("from")+":"),
            {
                id : "filter-date-from",
                xtype : "datefield"
            },{
                xtype: 'tbspacer',
                width: 10
            },
            new Ext.Toolbar.TextItem (AdMin.lang.translate("to")+":"),
            {
                id : "filter-date-to",
                xtype : "datefield"
            },{
                xtype: 'tbspacer',
                width: 10
            },{
                xtype : "tbbutton",
                text : "Filtrar",
                iconCls : "silk-funnel",
                handler : function () {
                    var date_to = Ext.getCmp("filter-date-to").getValue();
                    if(date_to != "") date_to = date_to.format("Y-m-d");

                    var date_from = Ext.getCmp("filter-date-from").getValue();
                    if(date_from != "") date_from = date_from.format("Y-m-d");

                    params = {
                        datef: date_from,
                        datet: date_to,
                        module: Ext.getCmp("filter-module").getValue(),
                        user: Ext.getCmp("filter-user").getValue()
                    };
                    Ext.apply(logStore.baseParams, params);
                    logStore.load({params : params});
                }
            },{
                xtype: 'tbspacer', width: 10
            },{
                xtype : "tbbutton",
                text : "reset",
                handler : function () {
                    Ext.getCmp("filter-date-from").reset();
                    Ext.getCmp("filter-date-to").reset();
                    Ext.getCmp("filter-module").reset();
                    Ext.getCmp("filter-user").reset();

                    var date_to = Ext.getCmp("filter-date-to").getValue();
                    if(date_to != "") date_to = date_to.format("Y-m-d");

                    var date_from = Ext.getCmp("filter-date-from").getValue();
                    if(date_from != "") date_from = date_from.format("Y-m-d");

                    params = {
                        datef: date_from,
                        datet: date_to,
                        module: Ext.getCmp("filter-module").getValue(),
                        user: Ext.getCmp("filter-user").getValue()
                    };
                    Ext.apply(logStore.baseParams, params);
                    logStore.load({params : params});
                }
            }
        ],
        task: {
            run: function() {
                if(Ext.getCmp("log-tab").isPaused == false)
                    logStore.reload();
            },
            interval: 4000
        },
        onTabChange: function () {
            logStore.load({ params: { start: 0, limit: AdMin.users.numMaxListedRows } });
            Ext.getCmp("log-tab").isPaused = true;
            Ext.TaskMgr.start(Ext.getCmp("log-tab").task);
            Ext.getCmp("pause_log_btn").setText("start");
            if(Ext.getCmp("log-tab").isPaused)
                logTooltip.show();
        },
        onReady: function(){
            alert("ready");
        },
        title: "Log",
        items: [logGrid],
        bbar: new Ext.PagingToolbar({
            pageSize: AdMin.users.numMaxListedRows,
            store: logStore,
            displayInfo: true,
            displayMsg: AdMin.lang.translate('displayin_n-m_of_p'),
            emptyMsg: AdMin.lang.translate('no_records_found'),
            items : [{
                xtype : "button",
                text : "start",
                id : "pause_log_btn",
                
                handler : function () {
                    var logTab = Ext.getCmp("log-tab");
                    
                    if(logTab.isPaused)
                    {
                        logTab.isPaused = false;
                        Ext.TaskMgr.start(logTab.task);
                        Ext.getCmp("pause_log_btn").setText( "pause");
                    }
                    else
                    {
                        logTab.isPaused = true;
                        Ext.TaskMgr.stop(logTab.task);
                        Ext.getCmp("pause_log_btn").setText("start");
                        logTooltip.show();
                    }
                }
            }]
        })
    });
    
    var logTooltip = new Ext.ToolTip({
        target:'pause_log_btn',
        id : 'tool-tip-logs',
        title:AdMin.lang.translate('Estado de logs'),
        anchor: 'right',
        html: AdMin.lang.translate('Los logs estan pausados en este momento, presione "start" para iniciar.'),
        autoHide: true,
        closable:true
    });
    
    var tabs = new Ext.TabPanel({
        region : "center",
        activeTab:0,
        flex:1,
        resizeTabs:true, // turn on tab resizing
        minTabWidth: 115,
        border: true,
        tabWidth:180,
        id : "users-module",
        enableTabScroll:true,
        defaults: {autoScroll:false},
        listeners : {
            "tabchange": function(main, tab) {
                if(tab.onTabChange)  tab.onTabChange(tab);
            }
        },
        plugins: new Ext.ux.TabCloseMenu(),
        items : [{
            xtype: "panel",
            border: false,
            layout: "border",
            title: ucfirst(AdMin.lang.translate('users')),
            items : [ usersPanel, userDetailsForm ]
        },{
            xtype: "panel",
            border: false,
            layout: "border",
            title: ucfirst(AdMin.lang.translate('roles')),
            items : [rolesGrid, rolePermissionsForm]
        },logPanel]
    });
    
    return tabs;
};
